//依赖
const gulp = require("gulp");
const connect = require("gulp-connect");
const concat = require("gulp-concat");
var sass = require('gulp-sass');
sass.compiler = require('node-sass');

const findSync = require("./utils/index").findSync;
const scssJSON  = require("./conf/index").scss;
const scripts  = require("./conf/index").scripts;

let scriptsPathArray = null;
let scriptsTaskArray = [];
let scssTaskArray = [];


//路径配置 获取当前路径下所有文件路径
function init(){
    let scriptsPathArr = findSync('./src/scripts').map(item=>{
        return './' + item.replace(/\\/g,'/');
     });
    const scriptsUnSaveArray = ["!./src/scripts/libs/*.js"];
    scriptsPathArr = scriptsPathArr.concat(scriptsUnSaveArray);
    mergeMyScripts(scripts)
    mergeMyScss(scssJSON)
}

//监听js改变
function watchScripts(json){
    for(let attr in json){
        gulp.watch(json[attr].src+'*.js',['scripts-' + attr]);
    }
}

function watchScss(json){
    for(let attr in json){
          gulp.watch(json[attr].src+"*.scss",["scss-"+attr])
    }
}

//分src合并js
function mergeMyScripts(json){
    for(let attr in json){
        scriptsTaskArray.push("scripts-"+attr)
        gulp.task('scripts-'+attr,()=>{
            return  gulp.src([scripts[attr].src+"*.js"])
            .pipe(concat(attr + '.js'))
            .pipe(gulp.dest('./dev/scripts'))
            .pipe(connect.reload());
        })
    }
}

function mergeMyScss(json){
    for(let attr in json){
        scssTaskArray.push("scss-"+attr)
        gulp.task('scss-'+attr,()=>{
            return  gulp.src([json[attr].src+"*.scss"])
            .pipe(concat(attr + '.scss'))
            .pipe(sass().on('error',sass.logError))
            .pipe(gulp.dest('./dev/stylesheets'))
            .pipe(connect.reload());
        })
    }
}



//转存html
gulp.task('html',()=>{
    return gulp.src(['./src/*.html'])
    .pipe(gulp.dest('./dev'))
    .pipe(connect.reload());
})

//监听html改变
gulp.task('watch',()=>{
    gulp.watch('./src/*.html',['html']);
    gulp.watch("./src/scss/index/*.scss",["scss"])
    watchScripts(scripts);
})

//建立服务器
gulp.task('connect',()=>{
    connect.server({
        root:'dev',
        livereload:true
    });
})


//总合并js
gulp.task('scripts',scriptsTaskArray)
//总合并scss
gulp.task('scss',scssTaskArray)

//启动服务器
gulp.task("default",["html",'scripts',"connect","watch"]);

gulp.task("gulp-dev",["html",'scripts','scss',"connect","watch"]);



init()

require('./gulp-build');